const Controller = require('egg').Controller;

class OrderController extends Controller {
    // 创建订单
    async create() {
        const { ctx, service } = this;

        try {
            // 参数验证
            const rules = {
                seller_id: { type: 'integer', required: true },
                goods_id: { type: 'integer', required: true },
                amount: { type: 'number', required: true }
            };
            ctx.validate(rules);

            const orderData = ctx.request.body;

            // 从token中获取买家ID
            const token = ctx.request.header.token;
            const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
            orderData.buyer_id = decode.user_id || decode.admin_id;

            const result = await service.order.create(orderData);

            ctx.body = {
                code: 0,
                data: result,
                msg: '订单创建成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '订单创建失败'
            };
        }
    }

    // 获取订单列表（支持分页和基础搜索）
    async list() {
        const { ctx, service } = this;

        try {
            const query = ctx.query;

            // 参数验证
            const rules = {
                page: { type: 'string', required: false },
                pageSize: { type: 'string', required: false },
                keyword: { type: 'string', required: false, allowEmpty: true },
                status: { type: 'string', required: false }
            };
            ctx.validate(rules);

            const result = await service.order.getOrders(query);

            ctx.body = {
                code: 0,
                data: result,
                msg: '获取成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取订单列表失败'
            };
        }
    }

    // 订单高级搜索
    async search() {
        const { ctx, service } = this;

        try {
            const searchParams = ctx.query;

            // 参数验证
            const rules = {
                page: { type: 'string', required: false },
                pageSize: { type: 'string', required: false },
                keyword: { type: 'string', required: false, allowEmpty: true },
                status: { type: 'string', required: false },
                buyer_name: { type: 'string', required: false, allowEmpty: true },
                seller_name: { type: 'string', required: false, allowEmpty: true },
                goods_title: { type: 'string', required: false, allowEmpty: true },
                start_date: { type: 'string', required: false },
                end_date: { type: 'string', required: false },
                min_amount: { type: 'string', required: false },
                max_amount: { type: 'string', required: false },
                order_by: { type: 'string', required: false },
                order_type: { type: 'string', required: false }
            };
            ctx.validate(rules);

            const result = await service.order.searchOrders(searchParams);

            ctx.body = {
                code: 0,
                data: result,
                msg: '搜索成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '订单搜索失败'
            };
        }
    }

    // 获取我的订单（支持搜索和分页）
    async myOrders() {
        const { ctx, service } = this;

        try {
            const { role = 'buyer', ...searchParams } = ctx.query;

            // 参数验证
            const rules = {
                role: { type: 'string', required: false, values: ['buyer', 'seller'] },
                page: { type: 'string', required: false },
                pageSize: { type: 'string', required: false },
                keyword: { type: 'string', required: false, allowEmpty: true },
                status: { type: 'string', required: false }
            };
            ctx.validate(rules);

            // 从token中获取用户ID
            const token = ctx.request.header.token;
            const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
            const userId = decode.user_id || decode.admin_id;

            const result = await service.order.getMyOrders(userId, role, searchParams);

            ctx.body = {
                code: 0,
                data: result,
                msg: '获取成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取我的订单失败'
            };
        }
    }

    // 获取订单统计
    async stats() {
        const { ctx, service } = this;

        try {
            // 从token中获取用户ID
            const token = ctx.request.header.token;
            const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
            const userId = decode.user_id || decode.admin_id;

            const stats = await service.order.getOrderStats(userId);

            ctx.body = {
                code: 0,
                data: stats,
                msg: '获取成功'
            };
        } catch (error) {
            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取订单统计失败'
            };
        }
    }

    // 获取订单详情
    async detail() {
        const { ctx, service } = this;

        try {
            const { id } = ctx.params;

            // 验证ID参数
            const rules = {
                id: { type: 'id', required: true }
            };
            ctx.validate(rules, ctx.params);

            const order = await service.order.getOrderById(id);

            ctx.body = {
                code: 0,
                data: order,
                msg: '获取成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取订单详情失败'
            };
        }
    }

    // 更新订单状态 - 修复权限检查
    async updateStatus() {
        const { ctx, service } = this;

        try {
            const { id } = ctx.params;
            const { status } = ctx.request.body;

            // 验证参数
            const paramRules = {
                id: { type: 'id', required: true }
            };
            ctx.validate(paramRules, ctx.params);

            const bodyRules = {
                status: { type: 'integer', required: true, min: 0, max: 4 }
            };
            ctx.validate(bodyRules);

            // 从token中获取用户ID和类型
            const token = ctx.request.header.token;
            const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
            const userId = decode.user_id || decode.admin_id;
            const userType = decode.type || 'user'; // 获取用户类型

            const result = await service.order.updateOrderStatus(id, status, userId, userType);

            ctx.body = {
                code: 0,
                data: result,
                msg: '订单状态更新成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '订单状态更新失败'
            };
        }
    }

    // 删除订单 - 修复权限检查
    async delete() {
        const { ctx, service } = this;

        try {
            const { id } = ctx.params;

            // 验证ID参数
            const rules = {
                id: { type: 'id', required: true }
            };
            ctx.validate(rules, ctx.params);

            // 从token中获取用户ID和类型
            const token = ctx.request.header.token;
            const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
            const userId = decode.user_id || decode.admin_id;
            const userType = decode.type || 'user'; // 获取用户类型

            await service.order.deleteOrder(id, userId, userType);

            ctx.body = {
                code: 0,
                data: null,
                msg: '订单删除成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '订单删除失败'
            };
        }
    }

    // 新增：管理员专用更新订单状态接口
    async adminUpdateStatus() {
        const { ctx, service } = this;

        try {
            const { id } = ctx.params;
            const { status } = ctx.request.body;

            // 验证参数
            const paramRules = {
                id: { type: 'id', required: true }
            };
            ctx.validate(paramRules, ctx.params);

            const bodyRules = {
                status: { type: 'integer', required: true, min: 0, max: 4 }
            };
            ctx.validate(bodyRules);

            // 验证管理员权限
            const token = ctx.request.header.token;
            const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
            if (decode.type !== 'admin') {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: '无权限操作'
                };
                return;
            }

            const result = await service.order.adminUpdateOrderStatus(id, status);

            ctx.body = {
                code: 0,
                data: result,
                msg: '订单状态更新成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '订单状态更新失败'
            };
        }
    }
}

module.exports = OrderController;